package com.endlessblue.visa.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.endlessblue.visa.model.User;
import com.endlessblue.visa.model.UserVisa;
import com.endlessblue.visa.model.UserVisaExample;
import com.endlessblue.visa.model.VisaHistory;
import com.endlessblue.visa.model.VisaHistoryExample;
import com.endlessblue.visa.service.SequenceService;
import com.endlessblue.visa.service.UserVisaService;
import com.endlessblue.visa.service.VisaHistoryService;
import com.endlessblue.visa.util.DateUtil;
import com.endlessblue.visa.util.JsonUtil;
import com.endlessblue.visa.util.RequestUtil;
import com.endlessblue.visa.util.SessionCacheUtil;
import com.endlessblue.visa.util.StringUtil;
import com.endlessblue.visa.vo.BusiCode;
import com.endlessblue.visa.vo.BusiResult;
import com.endlessblue.visa.vo.ReqParamCheck;
import com.endlessblue.visa.vo.ReqParamCheck.InterfaceType;


@RestController
@RequestMapping("/app/busi")
public class BusinessController{
	
	private final static Logger logger = LoggerFactory.getLogger(BusinessController.class);
	
	@Resource
	private UserVisaService userVisaService;
	@Resource
	private SequenceService sequenceService;
	@Resource
	private VisaHistoryService visaHistoryService;
	
	@RequestMapping(value = "/getVisaes", method = RequestMethod.POST)
	public BusiResult<Object> getVisaes(HttpServletRequest request){
		BusiResult<Object> ret = new BusiResult<Object>();
		User sUser = (User)SessionCacheUtil.getSessionMap(request).get("sUser");
		logger.info("获取签证列表：{}", sUser.getUserId());
		Map<String, String> params = RequestUtil.getParamMap(request.getParameterMap());
		String visaId = params.get("vid");
		UserVisaExample uvEp = new UserVisaExample();
		UserVisaExample.Criteria uvCr = uvEp.createCriteria();
		uvCr.andUserIdEqualTo(sUser.getUserId());
		if (visaId != null) {
			uvCr.andIdEqualTo(visaId);
		}
		uvEp.setOrderByClause("id DESC");
		List<UserVisa> visaList = userVisaService.selectByExample(uvEp);
		ret.setCoder(BusiCode.ERROR_0000);
		ret.setResult(visaList);
		logger.debug("获取成功，返回:{}", ret);
		return ret;
	}
	
	/**
	 * 同步客户端签证记录至服务端
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "syncVisaHis2Server", method = RequestMethod.POST)
	public BusiResult<Object> syncVisaHistory2Server(HttpServletRequest request) {
		BusiResult<Object> ret = new BusiResult<Object>();
		User sUser = (User)SessionCacheUtil.getSessionMap(request).get("sUser");
		logger.info("签证历史记录同步至服务端：{}", sUser.getUserId());
		Map<String, String> params = RequestUtil.getParamMap(request.getParameterMap());
		logger.debug("参数：{}", params);
		
		// 参数校验
		ret = ReqParamCheck.verify(ret, params, InterfaceType.SYNCVH2SERVER);
		if (!ret.isOk()) {
			logger.error("参数校验失败:{}", ret);
			return ret;
		}
		
		String visaId = params.get("vid"); // 被同步的签证ID
		String records = params.get("records");  // 记录：json格式
		List<Map<String, Object>> recordsList = JsonUtil.jsonToList(records);
		if (recordsList == null || recordsList.isEmpty()) {
			logger.error("无法同步，记录为空");
			return ret.setCode(BusiCode.ERROR_9005.getCode()).setMsg("同步记录为空（必须为json格式的list）");
		}
		UserVisa uv = userVisaService.selectByPrimaryKey(visaId);
		if (uv == null || !uv.getUserId().equals(sUser.getUserId())) {
			logger.error("无法根据ID：{}查找到对应签证", visaId);
			return ret.setCode(BusiCode.ERROR_9005.getCode()).setMsg("无对应签证");
		}
		
		List<Map<String, String>> syncBackList = new ArrayList<Map<String,String>>(); // 返回给客户端的已同步的记录
		// 开始同步对应签证
		for (Map<String, Object> map : recordsList) {
			Map<String, String> syncBackMap = new HashMap<String, String>();
			VisaHistory vh = new VisaHistory();
			String vhId = sequenceService.getCommonSequence();
			vh.setId(vhId);
			vh.setType(Integer.valueOf((String)map.get("type")));
			vh.setUserId(sUser.getUserId());
			vh.setVisaId(visaId);
			vh.setGenerateTime(DateUtil.formatDate((String)map.get("gTime")));
			vh.setCreateTime(new Date());
			String cid = (String)map.get("cid");
			int up = visaHistoryService.insert(vh);
			if (up == 1) {
				syncBackMap.put("cid", cid);
				syncBackMap.put("id", vhId);
			} else {
				logger.error("客户端记录：{},同步失败", cid);
			}
		}
		// 重新计算签证有效期
		if (userVisaService.calcUpdateVisaLeftTime(visaId)) {
			logger.info("更新签证有效期成功");
		} else {
			logger.info("更新签证有效期失败");
		}
		ret.setCoder(BusiCode.ERROR_0000).setAttach(syncBackList);
		return ret;
	}
	
	/**
	 * 同步服务端签证记录至客户端
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "syncVisaHis2Client", method = RequestMethod.POST)
	public BusiResult<Object> syncVisaHistory2Client(HttpServletRequest request) {
		BusiResult<Object> ret = new BusiResult<Object>();
		User sUser = (User)SessionCacheUtil.getSessionMap(request).get("sUser");
		logger.info("签证历史记录同步至客户端：{}", sUser.getUserId());
		Map<String, String> params = RequestUtil.getParamMap(request.getParameterMap());
		logger.debug("参数：{}", params);
		
		// 参数校验
		ret = ReqParamCheck.verify(ret, params, InterfaceType.SYNCVH2CLIENT);
		if (!ret.isOk()) {
			logger.error("参数校验失败:{}", ret);
			return ret;
		}
		
		String visaId = params.get("vid"); // 被同步的签证ID
		String lastGTime = params.get("lastGTime");  // 最后记录时间  -1 时为同步所有记录
		UserVisa uv = userVisaService.selectByPrimaryKey(visaId);
		if (uv == null || !uv.getUserId().equals(sUser.getUserId())) {
			logger.error("无法根据ID：{}查找到对应签证", visaId);
			return ret.setCode(BusiCode.ERROR_9005.getCode()).setMsg("无对应签证");
		}
		
		// 开始查询指定范围内记录
		VisaHistoryExample vhEx = new VisaHistoryExample();
		VisaHistoryExample.Criteria vhCr = vhEx.createCriteria();
		vhCr.andUserIdEqualTo(sUser.getUserId());
		vhCr.andVisaIdEqualTo(visaId);
		if (!"-1".equals(lastGTime)) {
			vhCr.andGenerateTimeGreaterThan(DateUtil.formatDate(lastGTime));
		}
		List<VisaHistory> vhList = visaHistoryService.selectByExample(vhEx);
		return ret.setCoder(BusiCode.ERROR_0000).setAttach(vhList);
	}
	
	/**
	 * 添加新签证
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addVisa", method = RequestMethod.POST)
	public BusiResult<Object> addVisa(HttpServletRequest request){
		BusiResult<Object> ret = new BusiResult<Object>();
		User sUser = (User)SessionCacheUtil.getSessionMap(request).get("sUser");
		logger.info("添加新的签证：{}", sUser.getUserId());
		Map<String, String> params = RequestUtil.getParamMap(request.getParameterMap());
		logger.debug("参数：{}", params);
		
		// 参数校验
		ret = ReqParamCheck.verify(ret, params, InterfaceType.ADDVISA);
		if (!ret.isOk()) {
			logger.error("参数校验失败:{}", ret);
			return ret;
		}
		
		UserVisa newUV = new UserVisa();
		newUV.setId(sequenceService.getCommonSequence());
		newUV.setVisaname(params.get("visaName"));
		newUV.setValidity(Integer.valueOf(params.get("validity")));
		newUV.setBeginTime(DateUtil.formatDate(params.get("beginTime")));
		int leftTime = newUV.getValidity();
		if (newUV.getBeginTime().getTime() < new Date().getTime()) {
			leftTime = DateUtil.calcDays(DateUtil.formatDate(params.get("beginTime")), new Date());
		}
		newUV.setLeftTime(leftTime);
		newUV.setTotalInTime(Integer.valueOf(params.get("totalInTime")));
		newUV.setLeftInTime(newUV.getTotalInTime());
		newUV.setStatus(1);
		newUV.setCreateTime(new Date());
		newUV.setUserId(sUser.getUserId());
		userVisaService.insertSelective(newUV);
		return ret.setCoder(BusiCode.ERROR_0000).setAttach(newUV);
	}
	
	
	/**
	 * 同步签证数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/syncVisaes", method = RequestMethod.POST)
	public BusiResult<Object> syncVisaes(HttpServletRequest request){
		BusiResult<Object> ret = new BusiResult<Object>();
		User sUser = (User)SessionCacheUtil.getSessionMap(request).get("sUser");
		logger.info("同步签证数据：{}", sUser.getUserId());
		Map<String, String> params = RequestUtil.getParamMap(request.getParameterMap());
		logger.info("参数：{}", params);
		
		// 参数校验
		ret = ReqParamCheck.verify(ret, params, InterfaceType.SYNC_VISA);
		if (!ret.isOk()) {
			logger.error("参数校验失败:{}", ret);
			return ret;
		}
		
		String planTime = params.get("planTime");
		String visaTime = params.get("visaTime");
		String tip = params.get("tip");
		String records = params.get("records");
		
		UserVisa upUserVisa = new UserVisa();
		upUserVisa.setId(sUser.getVisaId());
		if (StringUtil.isNotEmpty(planTime)) {
			upUserVisa.setPlanTime(planTime);
		}
		if (StringUtil.isNotEmpty(visaTime)) {
			upUserVisa.setVisaTime(visaTime);
		}
		if (StringUtil.isNotEmpty(tip)) {
			upUserVisa.setToTip(tip);
		}
		userVisaService.updateByPrimaryKeySelective(upUserVisa);
		
		if (StringUtil.isNotEmpty(records)) {
			List<Map<String, Object>> list = JsonUtil.jsonToList(records);
			if (list != null && !list.isEmpty()) {
				for (Map<String, Object> m : list) {
					VisaHistory upVH = new VisaHistory();
					upVH.setVisaId(sUser.getVisaId());
					upVH.setUserId(sUser.getUserId());
					if (StringUtil.isNotEmpty((String)m.get("inTime"))) {
						upVH.setInTime((String)m.get("inTime"));
					}
					if (StringUtil.isNotEmpty((String)m.get("outTime"))) {
						upVH.setOutTime((String)m.get("outTime"));
					}
					if ("0".equals(m.get("type"))) { // 添加
						upVH.setId(sequenceService.getCommonSequence());
						visaHistoryService.insertSelective(upVH);
						continue;
					}
					if ("1".equals(m.get("type"))) { // 修改
						upVH.setId((String)m.get("visaId"));
						visaHistoryService.updateByPrimaryKeySelective(upVH);
						continue;
					}
					if ("2".equals(m.get("type"))) { // 删除
						visaHistoryService.deleteByPrimaryKey((String)m.get("visaId"));
					}
				}
			}
		}
		UserVisa dbUV = userVisaService.selectByPrimaryKey(sUser.getVisaId());
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("planTime", dbUV.getPlanTime());
		result.put("tip", dbUV.getToTip());
		result.put("visaTime", dbUV.getVisaTime());
		List<Map<String, Object>> vhJsonList = new ArrayList<Map<String,Object>>();
		VisaHistoryExample vhEx = new VisaHistoryExample();
		vhEx.createCriteria().andVisaIdEqualTo(sUser.getVisaId()).andUserIdEqualTo(sUser.getUserId());
		List<VisaHistory> vhList = visaHistoryService.selectByExample(vhEx);
		if (vhList != null && !vhList.isEmpty()) {
			for (VisaHistory v : vhList) {
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("visaId", v.getId());
				m.put("inTime", v.getInTime());
				m.put("outTime", v.getOutTime());
				vhJsonList.add(m);
			}
		}
		result.put("records", JsonUtil.toJson(vhJsonList));
		ret.setResult(result);
		ret.setCoder(BusiCode.ERROR_0000);
		logger.info("返回:{}", ret);
		return ret;
	}
	
}
